package bsf.baseservice.businessmq.dal;


import bsf.baseservice.businessmq.model.tb_messagequeue_model;
import bsf.baseservice.businessmq.systemruntime.SystemParamConfig;
import bsf.db.DbConn;
import bsf.util.ConvertUtil;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

public class tb_messagequeue_dal
{
	public String TableName;

	public final long getMaxId(DbConn PubConn)
	{
			String cmd = String.format("select max(id) from %1$s s WITH(NOLOCK)", TableName);
			Object o = PubConn.executeScalar(cmd,new Object[]{});
			if (o == null)
			{
				return -1;
			}
			else
			{
				return ConvertUtil.objToInt64(o);
			}

	}

	public final ArrayList<tb_messagequeue_model> getMessages(DbConn PubConn, long lastmaxmessageid, int topcount)
	{

			java.util.ArrayList<tb_messagequeue_model> rs = new java.util.ArrayList<tb_messagequeue_model>();
			String cmd = String.format("select top %2$s * from %1$s s %3$s where id>? order by id asc",
					TableName, topcount, (SystemParamConfig.Consumer_ReadMessage_WithNolock==true?"with (nolock)":""));
			List<Map<String,Object>> ds = PubConn.executeList( cmd, new Object[]{lastmaxmessageid});
			if (ds != null && ds.size() > 0)
			{
				for (Map<String,Object> dr : ds)
				{
					tb_messagequeue_model o = createModel(dr);
					rs.add(o);
				}
			}
			return rs;

	}

	public boolean add2(DbConn PubConn, tb_messagequeue_model model)
	{
				//mq�������߶˵Ĵ���ʱ�䣨�����߶�ʱ����ܸ�������ʱ�䲻һ�£�
				//��Ϣ����,0=�ɶ���Ϣ��1=��Ǩ����Ϣ
				//��Դ����:0 ��ʾ ��������,1 ��ʾ Ǩ����Ϣ
				//��Ϣ�壨��Ϣ����,��json��ʽ�洢��Ϊ���Ķ����ǣ�
				//sql���ݽڵ㴦�Ĵ���ʱ��(�Թ�������ʱ��Ϊ׼)
		int rev = PubConn.executeSql(String.format("insert into %1$s(mqcreatetime,sqlcreatetime,state,source,message) " +
				"values(?,?,?,?,?)", TableName),
				new Object[]{model.mqcreatetime,model.sqlcreatetime,model.state,model.source,model.message});
		return rev == 1;

	}



	public tb_messagequeue_model createModel(Map<String,Object> dr)
	{
		tb_messagequeue_model o = new tb_messagequeue_model();

		//��Ϣid��,����1+���ݽڵ���+��������+ʱ�������+����id
		if (dr.containsKey("id"))
		{
			o.id= ConvertUtil.objToInt64(dr.get("id"));
		}
		//mq�������߶˵Ĵ���ʱ�䣨�����߶�ʱ����ܸ�������ʱ�䲻һ�£�
		if (dr.containsKey("mqcreatetime"))
		{
			o.mqcreatetime= ConvertUtil.objToDateTime(dr.get("mqcreatetime"));
		}
		//sql���ݽڵ㴦�Ĵ���ʱ��
		if (dr.containsKey("sqlcreatetime"))
		{
			o.sqlcreatetime= ConvertUtil.objToDateTime(dr.get("sqlcreatetime"));
		}
		//��Ϣ����,0=�ɶ���Ϣ��1=��Ǩ����Ϣ
		if (dr.containsKey("state"))
		{
			o.state= ConvertUtil.objToByte(dr.get("state"));
		}
		//��Դ����:0 ��ʾ ��������,1 ��ʾ Ǩ����Ϣ
		if (dr.containsKey("source"))
		{
			o.source= ConvertUtil.objToByte(dr.get("source"));
		}
		//��Ϣ�壨��Ϣ����,��json��ʽ�洢��Ϊ���Ķ����ǣ�
		if (dr.containsKey("message"))
		{
			o.message= ConvertUtil.nullToStr(dr.get("message"));
		}
		return o;
	}
}